#pragma once
#include <pthread.h>
#include <iostream>
#include <string>
namespace threadMould
{
    class ThreadDate
    {
    public:
        // 构造时会放一把全局锁进去
        ThreadDate(std::string name, pthread_mutex_t* mutex) : _name(name), _mutex(mutex)
        {
        }
        ~ThreadDate()
        {
        }

    public:
        std::string _name;
        pthread_mutex_t *_mutex;
    };
    typedef void (*func_t)(ThreadDate *td);
    class Thread
    {
    public:
        // 此时该线程能看到全局锁
        //初始化_func是为了后续传入this指针调用任务函数
        //初始化_td是为了看到一把全局锁
        Thread(std::string name, func_t func, ThreadDate *td)
            : _name(name), _func(func), _td(td)
        {
            std::cout << name << "has created" << std::endl;
        }
        void Excute()
        {
            std::cout<<_name<<"is running"<<std::endl;
            _isrunning = true;
            _func(_td);
            _isrunning = false;
        }
        //成员函数有this指针，需要定义为全局的
        static void* ThreadRoutine(void* args)
        {
            Thread* self = static_cast<Thread*>(args);
            self->Excute();
            return nullptr;
        }
        bool Start()
        {
            int n = pthread_create(&_tid,nullptr,ThreadRoutine,this);
            if(n != 0 )return false;
            else return true;
        }
        std::string Status()
        {
            if(_isrunning) return "running";
            else return "sleep";
        }
        void Stop()
        {
            if(_isrunning)
            {
                ::pthread_cancel(_tid);
                std::cout<<_name<<"has canceled"<<std::endl;
            }
        }
        void Join()
        {
            ::pthread_join(_tid,nullptr);
                std::cout<<_name<<"has exited"<<std::endl;
            delete _td;
        }
        ~Thread()
        {

        }

    private:
        std::string _name;
        pthread_t _tid;//输出形参数，可以在pthread_creat时添入正确的值
        bool _isrunning;
        func_t _func;
        ThreadDate *_td; // 数据里面包含一把锁
    };
}